﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Odbc;
using System.IO;

namespace CITPRO.Linq.LinqToOdbc {
    /// <summary>
    /// Bulk exports specified
    /// data to tab delimited format file with no header column
    /// </summary>
    public class BulkExportReaderConvertor : IOdbcReaderConvertor {

        private BulkExportConfig config;
        public BulkExportReaderConvertor(BulkExportConfig config) {
            this.config = config;
            if (config.ColumnDelimiter == null) config.ColumnDelimiter = "\t";
            if (config.RowDelimiter == null) config.RowDelimiter = "\n";
            var dir = Path.GetDirectoryName(config.ExportFilePath);
            if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
        }

        public ICollection<T> GetList<T>(OdbcDataReader reader) {
            using (var fileStream = new FileStream(config.ExportFilePath, FileMode.Append))
            using (var writer = new StreamWriter(fileStream)) {
                while (reader.Read()) {
                    config.AffectedRecords++;
                    var line = string.Join(config.ColumnDelimiter, (Enumerable.Range(0, reader.FieldCount).Select(e => reader[e])));
                    writer.Write("{0}{1}", line, config.RowDelimiter);
                }
            }
            return new List<T>();
        }

        public void SetRowReadHandler(Type type, Func<object, bool> handler) {
            throw new NotImplementedException();
        }

        public void ClearRowReadHandler(Type type) {
            throw new NotImplementedException();
        }

        public void ClearAllRowReadHandlers() {
            throw new NotImplementedException();
        }
    }
}
